package com.yixing.demo.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class UserOnlineStatus {
    private ConcurrentHashMap<Integer, WebSocketSession> hashMap = new ConcurrentHashMap<>();

    public boolean online(int userId, WebSocketSession session) {
           if(hashMap.get(userId) != null) {
               log.info("已经登录过了，不能多开");
               return false;
           }else {
               hashMap.put(userId, session);
               log.info("上线");
               return true;
           }
    }

    public void offline(int userId, WebSocketSession session) {
        WebSocketSession sessionInHashMap = hashMap.get(userId);
        if(sessionInHashMap != session) {
            return;
        }else {
            hashMap.remove(userId);
            log.info("下线");
        }
    }

    public WebSocketSession getWebSocketSessionByUserId(int userId) {
        return hashMap.get(userId);
    }
}
